#!/usr/bin/env bash
set -eo pipefail

declare -r SCRIPT_DIR=$(cd $(dirname $0) >/dev/null 2>&1 && pwd)
declare -r V1_DB_PATH=$(dirname ${SCRIPT_DIR})/tmp/v1db
source ${SCRIPT_DIR}/common.sh

declare -r tag=$1 container_name=$2 data=$3 config=$4 logs=$5

log_msg Getting default config
if ! docker run --rm influxdb:${tag} influxd print-config > ${config}/default-config.yml; then
    log_msg Error: Failed to extract default config
    exit 1
fi
sed -e 's#/var/lib/influxdb2#/home/influxdb/influxdb2#g' -e 's#:8086#:9000#g' ${config}/default-config.yml > ${config}/config.yml

declare -r v1_config=${V1_DB_PATH}/influxdb.conf
cat > ${v1_config} <<'EOF'
[meta]
  dir = "/home/influxdb/v1/meta"

[data]
  dir = "/home/influxdb/v1/data"
  engine = "tsm1"
  wal-dir = "/home/influxdb/v1/wal"

[http]
  bind-address = ":9000"
EOF

declare -ra docker_run_influxd=(
    docker run -i -d
    --name=${container_name}
    -u $(id -u):influxdb
    -p 8086:9000
    -v ${data}:/home/influxdb/influxdb2
    -v ${config}:/etc/influxdb2
    -v ${V1_DB_PATH}:/home/influxdb/v1
    -e DOCKER_INFLUXDB_INIT_UPGRADE_V1_CONFIG=/home/influxdb/v1/influxdb.conf
    -e DOCKER_INFLUXDB_INIT_MODE=upgrade
    -e DOCKER_INFLUXDB_INIT_USERNAME=${TEST_USER}
    -e DOCKER_INFLUXDB_INIT_PASSWORD=${TEST_PASSWORD}
    -e DOCKER_INFLUXDB_INIT_ORG=${TEST_ORG}
    -e DOCKER_INFLUXDB_INIT_BUCKET=${TEST_BUCKET}
    -e DOCKER_INFLUXDB_INIT_RETENTION=${TEST_RETENTION_SECONDS}s
    influxdb:${tag} influxd run
)

log_msg Booting 2.x container in upgrade mode with custom config
if ! ${docker_run_influxd[@]} > /dev/null; then
    log_msg Error: Failed to launch container
    exit 1
fi
wait_container_ready

log_msg Checking onboarding API post-upgrade
declare onboarding_allowed=$(curl -s localhost:8086/api/v2/setup | jq .allowed)
if [[ ${onboarding_allowed} != 'false' ]]; then
    log_msg Error: Onboarding allowed post-upgrade
    exit 1
fi

log_msg Tearing down 2.x container
docker stop ${container_name} > /dev/null
docker logs ${container_name} > ${logs}/init-docker-stdout.log 2> ${logs}/init-docker-stderr.log
docker rm ${container_name} > /dev/null

if [ ! -f ${data}/influxd.bolt ]; then
    log_msg Error: BoltDB not persisted to host directory
    exit 1
fi

log_msg Booting another 2.x container
if ! ${docker_run_influxd[@]} > /dev/null; then
    log_msg Error: failed to launch container
    exit 1
fi
wait_container_ready

log_msg Checking onboarding API after recreating container
onboarding_allowed=$(curl -s localhost:8086/api/v2/setup | jq .allowed)

if [[ ${onboarding_allowed} != 'false' ]]; then
    log_msg Error: Onboarding allowed after recreating container
    exit 1
fi
